package kr.hkit.androidcomplete03.ch27;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class DownloadManagerEx extends Activity {

	DownloadManager mDm;
	long mId = 0;
	ImageView image;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downloadmanager);
		mDm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
		image = (ImageView) findViewById(R.id.image);
	}

	public void onPause() {
		super.onPause();
		if (mId != 0) {
			unregisterReceiver(mDownComplete);		// BroadCast를 지우는 것
		}
	}

	BroadcastReceiver mDownComplete = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "다운로드 완료", Toast.LENGTH_LONG).show();
		}
	};

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.btnqueue:
			Uri uri = Uri
					.parse("http://developer.android.com/images/home/kk-hero.jpg");		// 해당URL을 불러들임.
			DownloadManager.Request req = new DownloadManager.Request(uri);				// DownloadManager에 필요한 요구
			req.setTitle("테스트 다운로드");						// 해당 파일명
			req.setDescription("이미지 파일을 다운로드 받습니다.");	// 파일에 대한 부연설명
			req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
					| DownloadManager.Request.NETWORK_MOBILE);			// 다운로드 받기 위해서 권한 부여
			mId = mDm.enqueue(req);							// 큐 형태로 FIFO구조
			IntentFilter filter = new IntentFilter();
			filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
			registerReceiver(mDownComplete, filter);		// 필터에 해당하는 것만 받아들인다.
			break;

		case R.id.btnview:
			try {
				ParcelFileDescriptor file;
				file = mDm.openDownloadedFile(mId);
				FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(
						file);
				Bitmap bm = BitmapFactory.decodeStream(fis);
				image.setImageBitmap(bm);
			} catch (FileNotFoundException e) {
				Toast.makeText(this, "파일이 없음", Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btndelete:
			if (mDm.remove(mId) == 1) {
				Toast.makeText(this, "삭제 완료", Toast.LENGTH_LONG).show();
				image.setImageBitmap(null);
			}
			break;
		}// end of switch
	}// end of mOnClick
}// end of class
